<template>
  <ebook-dialog :title="title" ref="dialog">
    <div class="dialog-list-wrapper" v-if="!ifNewGroup">
      <!-- 分组类型列表 -->
      <div  v-for="(item, index) in categoryList" :key="index">
        <!-- edit===1表示新建分组，edit===2表示移出分组，只有在进入分组里面才会出现 -->
        <div class="dialog-list-item"
            :class="{'is-add': item.edit  ? item.edit === 1 : false}"
            @click="onGroupClick(item)"
            v-if="(item.edit === 2 && isInGroup) || item.edit !== 2 || !item.edit">
          <div class="dialog-list-item-text">{{item.groupName || item.title}}</div>
          <!-- shelfCategory当前进入的分组，本分组后面会有一个勾勾，isInGroup是否再分组里 -->
          <div class="dialog-list-icon-wrapper" v-if="isInGroup && shelfCategory.groupId === item.groupId">
            <span class="icon-check"></span>
          </div>
        </div>
      </div>
    </div>
    <!--是新增状态  -->
    <div class="dialog-new-group-wrapper" v-else>
      <div class="dialog-input-title-wrapper">
        <span class="dialog-input-title">{{$t('shelf.groupName')}}</span>
      </div>
      <div class="dialog-input-wrapper">
        <div class="dialog-input-inner-wrapper">
          <input type="text" class="dialog-input" v-model="newGroupName" ref="dialogInput">
          <div class="dialog-input-clear-wrapper" @click="clear" v-show="newGroupName && newGroupName.length > 0">
            <span class="icon-close-circle-fill"></span>
          </div>
        </div>
      </div>
    </div>
    <!--  -->
    <div slot="btn" class="group-dialog-btn-wrapper">
      <div class="dialog-btn" @click="hide">{{$t('shelf.cancel')}}</div>
      <div class="dialog-btn" @click="createNewGroup" :class="{'is-empty': newGroupName && newGroupName.length === 0}"
           v-if="ifNewGroup">{{$t('shelf.confirm')}}
      </div>
    </div>
  </ebook-dialog>
</template>

<script>
  // 重命名dialog
  import EbookDialog from '../common/Dialog'
  import { storeShelfMixin } from '../../utils/mixin'
  import { removeAddFromShelf, appendAddToShelf } from '../../utils/store'
  import { saveBookShelf } from '../../utils/localStorage'
  import { changeGroup, getGroupList, shelf, updateGroupName } from '../../api/store'
  import { GETGROUPLIST } from '../../api'

  export default {
    name: 'group-dialog',
    mixins: [storeShelfMixin],
    components: {
      EbookDialog
    },
    props: {
      // 一打开直接进入编辑分组名称这个对话框
      showNewGroup: {
        type: Boolean,
        default: false
      },
      // 传入分组名
      groupName: String
    },
    computed: {
      isInGroup() {
        // 判断是否再分组列表中
        return this.currentType === 2
      },
      defaultCategory() {
        return [
          {
            title: this.$t('shelf.newGroup'),
            edit: 1
          },
          {
            title: this.$t('shelf.groupOut'),
            edit: 2
          }
        ]
      },
      categoryList() {
        return [...this.defaultCategory, ...this.category]
      },
      title() {
        return !this.ifNewGroup ? this.$t('shelf.moveBook') : this.$t('shelf.newGroup')
      }
    },
    data() {
      return {
        ifNewGroup: false,
        newGroupName: '',
        category: []
      }
    },
    methods: {
      // 打开的时候进行赋值，dialog弹框显示什么状态实际上又data里面的ifNewGroup控制的
      show() {
        this.ifNewGroup = this.showNewGroup
        this.newGroupName = this.groupName
        this.$refs.dialog.show()
      },
      hide() {
        // 将dialog弹窗隐藏
        this.$refs.dialog.hide()
        setTimeout(() => {
          // 新增状态为false，下次打开为列表，而不会显示新增的页面
          this.ifNewGroup = false
        }, 200)
      },
      onGroupClick(item) {
        console.log('item', item)
        // 移入分组情况
        // edit===1表示新建分组，edit===2表示下面的移出分组，这个移出分组只有在进入分组里才会出现
        if (item.edit && item.edit === 1) {
          this.ifNewGroup = true
          // 移出分组情况
        } else if (item.edit && item.edit === 2) {
          console.log('移出分组item', item)
          this.moveOutFromGroup(item)
        } else {
          // /移入分组
          this.moveToGroup(item)
        }
      },
      clear() {
        this.newGroupName = ''
      },
      // 移入分组的算法,将书籍加入到指定的分组的实现
      moveToGroup(group) {
        // 看选中的书籍是否在我们vuex的书架中，如果在vuex的书架中就将他删除
        // 遍历书架里面的书籍,找到这本书,然后看这本书是不是存在于我们的shelfSelected这个数组里面，shelfSelected表示当前选中的书籍，如果这本书在shelfSelected里面，那么我们就将他过滤调
        this.setShelfList(this.shelfList
          .filter(book => {
            // 当为分组里的时候
            if (book.list) {
              book.list = book.list.filter(subBook =>
              this.shelfSelected.indexOf(subBook) < 0)
            }
            return this.shelfSelected.indexOf(book) < 0
          }))
          // 对书架的数组进行更新，得到不在选中图书里的图书
          .then(() => {
            // group就是我们选中的分组，我们将电子书加到这个分组。group.list表示当前这个分组下面的电子书
            if (group && group.list) {
              // 将group.list和shelfSelected合并
              group.list = [...group.list, ...this.shelfSelected]
            }
            console.log('移动到的分组', group)
            // API移入分组。map返回的是数组
            const bookNames = this.shelfSelected.map(item => item.fileName)
            console.log('bookName', bookNames)
            // 移动分组的API
            changeGroup(group.groupId, bookNames).then(res => {
              console.log('移动分组返回', res)
              // 更新书架列表
              shelf().then(response => {
                if (response && response.result) {
                  console.log('书架列表', response.result)
                  const list = appendAddToShelf(response.result)
                  // 存到localForage中
                  saveBookShelf(list)
                  // 将书架列表存到vuex里，return一个promise对象出去
                  this.setShelfList(list)
                  // 更新分组列表
                  if (this.currentType === 2) {
                    this.getCategoryList(this.shelfCategory.groupName)
                  }
                }
              })
            })
            // 合并完成后，foreach循环改变他的id对合并数组里面的电子书，进行重新的排序
            // group.list.forEach((item, index) => {
            //   item.id = index + 1
            // })
            // this.simpleToast(this.$t('shelf.moveBookInSuccess').replace('$1', group.groupName))
            this.$emit('showMyToast', this.$t('shelf.moveBookInSuccess').replace('$1', group.groupName))
            this.onComplete()
          })
      },
      // 移出分组方法
      moveOutFromGroup(group) {
        const bookNames = this.shelfSelected.map(item => item.fileName)
        console.log('移出分组的bookName数组', bookNames)
        changeGroup('默认分组', bookNames).then(res => {
          console.log('移动分组返回,移出分组后重新获取书架列表更新', res)
          // 更新书架列表
          shelf().then(response => {
            if (response && response.result) {
              console.log('书架列表', response.result)
              const list = appendAddToShelf(response.result)
              // 存到localForage中
              saveBookShelf(list)
              // 将书架列表存到vuex里，return一个promise对象出去
              this.setShelfList(list)
              // 更新分组列表
              if (this.currentType === 2) {
                this.getCategoryList(this.shelfCategory.groupName)
              }
            }
          })
        })
        this.$emit('showMyToast', this.$t('shelf.moveBookInSuccess').replace('$1', group.groupName))
        this.onComplete()
      },
      // 新建分组
      createNewGroup() {
        // 分组名不存在，就不会新建分组
        if (!this.newGroupName || this.newGroupName.length === 0) {
          return
        }
        // this.showNewGroup为true表示我们打开时就是要来编辑他的名称的,否则就是我们就会做分组的新增
        if (this.showNewGroup) {
          console.log('修改分组名，当前进入的分组id，新的分组名', this.shelfCategory.groupId, this.newGroupName)
          this.shelfCategory.groupName = this.newGroupName
          // 修改分组名API
          updateGroupName(this.shelfCategory.groupId, this.newGroupName).then(res => {
            console.log('修改分组名API返回的数据', res)
          })
          this.onComplete()
        } else {
          // API移入分组。map返回的是操作后的数组
          const bookNames = this.shelfSelected.map(item => item.fileName)
          console.log('bookName', bookNames)
          // 移动分组的API
          changeGroup(this.newGroupName, bookNames).then(res => {
            console.log('新建分组返回', res)
            // 接口获取书架列表，更新vuex书架列表和localStorage
            return shelf()
          }).then(response => {
            console.log('重新获取书架', '')
              if (response && response.result) {
                console.log('新建分组更新书架列表', response.result)
                const list = appendAddToShelf(response.result)
                // 将书架列表存到localStorage
                saveBookShelf(list)
                // 将书架列表存到vuex里
                this.setShelfList(list)
                if (this.shelfList) {
                  this.hide()
                  this.setIsEditMode(false)
                }
              }
            })
        }
        // // 接口获取书架列表，更新vuex书架列表和localStorage
        // shelf().then(response => {
        //   if (response && response.result) {
        //     console.log('新建分组更新书架列表', response.result)
        //     const list = appendAddToShelf(response.result)
        //     // 将书架列表存到localStorage
        //     saveBookShelf(list)
        //     // 将书架列表存到vuex里
        //     this.setShelfList(list)
        //     if (this.shelfList) {
        //       this.hide()
        //       this.setIsEditMode(false)
        //     }
        //   }
        // })
        // 如果不为空，建一个分组的对象，把分组对象加入到，书架数组中并且进行保存
        // if (this.showNewGroup) {
        //   this.shelfCategory.groupName = this.newGroupName
        //   this.onComplete()
        // } else {
        //   // 新建的分组的group对象
        //   const group = {
        //     // id书架元素中倒数第二个元素+1
        //   // id: this.shelfList[this.shelfList.length - 2].id + 1,
        //   list: [],
        //   // selected: false,
        //   groupId: this.shelfList[this.shelfList.length - 2].id + 1,
        //   groupName: this.newGroupName,
        //   type: 2,
        //   selected: false
        //   }
        //   let list = removeAddFromShelf(this.shelfList)
        //   list.push(group)
        //   list = appendAddToShelf(list)
        //   // 将书架保存到vuex中
        //   this.setShelfList(list).then(() => {
        //     this.onComplete()
        //     // this.moveToGroup(group)
        //   })
        // }
      },
      onComplete() {
        // saveBookShelf(this.shelfList)
        this.hide()
        this.setIsEditMode(false)
      }
    },
    created () {
      // API获取dialog弹窗显示的分组列表
      getGroupList().then(({ groupList }) => {
        this.category = groupList.filter(group => group.groupName !== '默认分组')
        console.log('dialog分组列表显示', this.categoryList)
      })
    }
  }
</script>

<style lang="scss" rel="stylesheet/scss" scoped>
  @import "../../assets/styles/global";

  .dialog-list-wrapper {
    width: 100%;
    padding: 0 px2rem(20);
    box-sizing: border-box;
    font-size: px2rem(14);
    @include scroll;
    .dialog-list-item {
      display: flex;
      padding: px2rem(15) 0;
      box-sizing: border-box;
      color: #666;
      &.is-add {
        color: $color-blue;
        &:active {
          color: $color-blue-transparent;
        }
      }
      &:active {
        color: rgba(102, 102, 102, .5)
      }
      .dialog-list-item-text {
        flex: 1;
      }
      .dialog-list-icon-wrapper {
        flex: 0 0 px2rem(30);
        color: $color-blue;
        @include right;
      }
    }
  }

  .dialog-new-group-wrapper {
    width: 100%;
    padding: 0 px2rem(20);
    box-sizing: border-box;
    .dialog-input-title-wrapper {
      font-size: px2rem(10);
      margin-top: px2rem(20);
    }
    .dialog-input-wrapper {
      width: 100%;
      padding: 0 0 px2rem(30) 0;
      box-sizing: border-box;
      .dialog-input-inner-wrapper {
        display: flex;
        width: 100%;
        padding: px2rem(10) 0;
        box-sizing: border-box;
        border-bottom: px2rem(1) solid #eee;
        font-size: px2rem(14);
        color: #666;
        .dialog-input {
          flex: 1;
          border: none;
          &:focus {
            outline: none;
          }
        }
        .dialog-input-clear-wrapper {
          flex: 0 0 px2rem(30);
          color: #ccc;
          @include center;
          &:active {
            color: #999;
          }
        }
      }
    }
  }

  .group-dialog-btn-wrapper {
    width: 100%;
    @include center;
  }
  .dialog-btn {
    flex: 1;
    &.is-empty {
      color: rgba(255, 255, 255, .5);
    }
    &:active {
      color: rgba(255, 255, 255, .5)
    }
  }
</style>
